package thesis.filesharing.web.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import thesis.filesharing.common.util.Utils;
import thesis.filesharing.resources.Constants;
import thesis.filesharing.services.fulltextsearch.indexing.DocumentQuery;
import thesis.filesharing.services.fulltextsearch.indexing.Operators;
import thesis.filesharing.services.fulltextsearch.indexing.QueryBuilder;
import thesis.filesharing.web.viewmodel.ajaxbeans.TagBean;

import com.google.appengine.api.search.Field;
import com.google.appengine.api.search.Results;
import com.google.appengine.api.search.ScoredDocument;

@Controller
public class ExerciseCategoryController {
	
	@PreAuthorize("hasRole('ROLE_LECTURER')")
	@RequestMapping(value = "/lecturer/searchTagsAjax", method = RequestMethod.GET)
	public void searchTagsAjax(@RequestParam("q") String q, HttpServletResponse response) throws IOException {
		response.setContentType("application/json");
		PrintWriter out = response.getWriter();
		
		q = Utils.insertSignChar(Utils.filterVietnameseSign(q));
		if (q.trim().length() > 0) {
			QueryBuilder builder = new QueryBuilder();
			String query = builder.add("fCategoryName", q, Operators.COLON).buildQuery();
			
			Results<ScoredDocument> results = DocumentQuery.search(query, Constants.SEARCH_INDEX_NAME);
			List<TagBean> tagBeans = new ArrayList<TagBean>();
			
			for (ScoredDocument result : results) {
				Iterator<Field> fields = result.getFields().iterator();
				
				Field f = null;
				String fieldName = null;
				TagBean tagBean = new TagBean();
				
				while (fields.hasNext()) {
					f = fields.next();
					fieldName = f.getName();
					
					if ("categoryName".equals(fieldName)) {
						tagBean.setCategoryName(f.getText());
					} else if ("ranking".equals(fieldName)) {
						tagBean.setRanking(Long.parseLong(f.getText()));
					}
				}
				
				tagBeans.add(tagBean);
			}
			
			ObjectMapper mapper = new ObjectMapper();
			out.print(mapper.writeValueAsString(tagBeans));
		} else {
			out.print("[]");
		}
	}
}
